import com.luojiaoj.User
import com.luojiaoj.Role
import com.luojiaoj.UserRole
import com.luojiaoj.subject.Category

class BootStrap {

    def init = { servletContext ->
        def admin = Role.findOrCreateWhere(authority: 'ROLE_ADMIN')
        if(!admin.id){
            admin.save(flush: true)
        }

        def user = Role.findOrCreateWhere(authority: 'ROLE_USER')
        if(!user.id){
            user.save(flush: true)
        }

        createTestUser('admin', 'admin', 'admin@test.org', admin)
        createTestUser('guancloud', 'guancloud', 'guancloud@test.org', admin)
        createTestUser('user001', 'user001', 'user001@test.org', user)
        createTestUser('user002', 'user002', 'user002@test.org', user)
        createTestUser('user003', 'user003', 'user003@test.org', user)
        createTestUser('user004', 'user004', 'user004@test.org', user)
        createTestUser('user005', 'user005', 'user005@test.org', user)

        createTestCategory("vol_1")
        createTestCategory("vol_2")
        createTestCategory("vol_3")
        createTestCategory("vol_4")

    }
    def destroy = {
    }

    private createTestUser(username, password, email, role) {
        def user = User.findByUsername(username);

        if (!user) {
            user = new User(username: username, password: password,
                    email: email, enabled: true, passwordExpired: false, accountLocked: false, accountExpired: false).save(failInError: true);
            assert user.id;
        }

        def adminUserRole = UserRole.findByUserAndRole(user, role);

        if (!adminUserRole) {
            UserRole.create(user, role, true);
        }

        return user
    }

    private createTestCategory(name) {
        new Category(name: name).save(failOnError: true)
    }
}
